<template>
  <div class="product-manager">
    <!-- 顶部统计卡片 -->
    <el-row :gutter="20" class="statistics">
      <el-col :span="6" v-for="stat in statistics" :key="stat.title">
        <el-card shadow="hover">
          <div class="stat-value">{{ stat.value }}</div>
          <div class="stat-title">{{ stat.title }}</div>
          <div
            class="stat-trend"
            :class="{ up: stat.trend > 0, down: stat.trend < 0 }"
          >
            较上月{{ stat.trend > 0 ? "+" : "" }}{{ stat.trend }}%
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作栏 -->
    <div class="action-bar">
      <div class="left">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增秒杀商品
        </el-button>
      </div>
      <div class="right">
        <el-select v-model="searchForm.status" placeholder="商品状态" clearable>
          <el-option label="待预热" :value="0" />
          <el-option label="预热中" :value="1" />
          <el-option label="进行中" :value="2" />
          <el-option label="已结束" :value="3" />
        </el-select>
        <el-input
          v-model="searchForm.keyword"
          placeholder="搜索商品名称/ID"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-input>
      </div>
    </div>

    <!-- 商品列表 -->
    <el-table :data="productList" stripe border v-loading="loading">
      <el-table-column prop="id" label="商品ID" width="80" />
      <el-table-column prop="image" label="商品图片" width="100">
        <template #default="{ row }">
          <el-image
            :src="row.image"
            :preview-src-list="[row.image]"
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="商品名称" />
      <el-table-column prop="price" label="原价" width="100">
        <template #default="{ row }"> ¥{{ row.price }} </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" width="100" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="seckillStatusTagType(row.seckillStatus)">
            {{ seckillStatusText(row.seckillStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)"
            >编辑</el-button
          >
          <el-button
            :type="row.status === 1 ? 'warning' : 'success'"
            size="small"
            @click="handleToggleStatus(row)"
          >
            {{ row.status === 1 ? "下架" : "上架" }}
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 商品编辑抽屉 -->
    <el-drawer
      v-model="showDrawer"
      :title="isEdit ? '编辑秒杀商品' : '新增秒杀商品'"
      size="85%"
      :destroy-on-close="true"
    >
      <div class="product-form">
        <el-form
          :model="productForm"
          :rules="rules"
          ref="productFormRef"
          label-width="100px"
        >
          <div class="form-content">
            <div class="left-section">
              <el-form-item label="选择商品" prop="goodsId">
                <el-autocomplete
                  v-model="productSearchInput"
                  :fetch-suggestions="querySearchProduct"
                  placeholder="请输入商品名称/ID"
                  @select="handleProductSelect"
                  style="width: 100%"
                />
              </el-form-item>
              <el-form-item label="商品名称">
                <el-input v-model="productForm.goodsName" disabled />
              </el-form-item>
              <el-form-item label="商品图片">
                <template v-if="!productForm.goodsId">
                  <div
                    class="image-slot"
                    style="width:160px;height:160px;display:flex;align-items:center;justify-content:center;background:#f5f7fa;border:1px dashed #dcdfe6;border-radius:6px;"
                  >
                    <el-icon
                      style="font-size:48px;color:#c0c4cc;"
                    ><icon-picture /></el-icon>
                  </div>
                </template>
                <template v-else>
                  <el-image
                    v-if="productForm.goodsImage"
                    :src="productForm.goodsImage"
                    style="width: 160px; height: 160px"
                    fit="cover"
                  />
                  <el-image
                    v-else
                    src="https://via.placeholder.com/80x80?text=商品图片"
                    style="width: 160px; height: 160px"
                    fit="cover"
                    :preview-src-list="[]"
                  >
                    <template #error>
                      <div class="image-slot">
                        <el-icon><icon-picture /></el-icon>
                      </div>
                    </template>
                  </el-image>
                </template>
              </el-form-item>
              <el-form-item label="商品简介">
                <el-input
                  type="textarea"
                  v-model="productForm.goodsBrief"
                  rows="3"
                  show-word-limit
                  maxlength="255"
                  disabled
                />
              </el-form-item>
            </div>
            <div class="right-section">
              <el-form-item label="原价">
                <el-input-number
                  v-model="productForm.originalPrice"
                  :precision="2"
                  :step="10"
                  :min="0"
                  style="width: 180px"
                  disabled
                />
                <span class="unit">元</span>
              </el-form-item>
              <el-form-item label="秒杀价格" prop="seckillPrice">
                <el-input-number
                  v-model="productForm.seckillPrice"
                  :precision="2"
                  :step="10"
                  :min="0"
                  style="width: 180px"
                />
                <span class="unit">元</span>
              </el-form-item>
              <el-form-item label="秒杀库存" prop="stock">
                <el-input-number
                  v-model="productForm.stock"
                  :min="0"
                  :step="1"
                  style="width: 180px"
                />
                <span class="unit">件</span>
              </el-form-item>
              <el-form-item label="秒杀时间" prop="seckillTime">
                <el-date-picker
                  v-model="productForm.seckillTime"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  style="width: 380px"
                />
              </el-form-item>
              <el-form-item label="秒杀状态" prop="seckillStatus">
                <el-select
                  v-model="productForm.seckillStatus"
                  placeholder="请选择"
                >
                  <el-option label="待预热" :value="0" />
                  <el-option label="预热中" :value="1" />
                  <el-option label="进行中" :value="2" />
                  <el-option label="已结束" :value="3" />
                </el-select>
              </el-form-item>
            </div>
          </div>
          <div class="detail-section">
            <el-form-item label="商品详情">
              <div class="editor-container">
                <template v-if="productForm.goodsId">
                  <Toolbar
                    style="border-bottom: 1px solid #ccc"
                    :editor="editorRef"
                    :defaultConfig="toolbarConfig"
                    mode="default"
                  />
                  <Editor
                    style="width: 100%; height: 600px"
                    v-model="productForm.goodsDetail"
                    :defaultConfig="editorConfig"
                    mode="default"
                    :readOnly="true"
                  />
                </template>
                <template v-else>
                  <div class="empty-detail-tip">请先选择商品</div>
                </template>
              </div>
            </el-form-item>
          </div>
        </el-form>
        <div class="drawer-footer">
          <el-button @click="showDrawer = false">取消</el-button>
          <el-button type="primary" @click="saveProduct">确定</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Plus,
  Delete,
  Edit,
  FolderAdd,
  InfoFilled,
  Search,
} from "@element-plus/icons-vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css";
import {
  uploadProductImage,
  getProductCategoryList,
  addProductCategory,
  updateProductCategory,
  deleteProductCategory,
} from "@/api/api"; // 上传图片的API

// 模拟数据
const mockProducts = Array.from({ length: 100 }).map((_, index) => ({
  id: index + 1,
  name: `商品${index + 1}`,
  image: `https://picsum.photos/200/200?random=${index}`,
  price: Math.floor(Math.random() * 1000) + 99,
  stock: Math.floor(Math.random() * 1000),
  status: Math.random() > 0.5 ? 1 : 0,
  description: `这是商品${index + 1}的详细描述...`,
}));

// 商品模拟数据（用于商品选择联想）
const allProducts = Array.from({ length: 100 }).map((_, index) => ({
  id: index + 1,
  name: `商品${index + 1}`,
  image: `https://picsum.photos/200/200?random=${index}`,
  price: Math.floor(Math.random() * 1000) + 99,
  brief: `商品${index + 1}简介...`,
  detail: `这是商品${index + 1}的详细描述...`,
}));

// 统计数据
const statistics = ref([
  { title: "秒杀商品总数", value: 156, trend: 12.3 },
  { title: "预热中", value: 23, trend: 5.1 },
  { title: "进行中", value: 45, trend: 8.9 },
  { title: "已结束", value: 88, trend: -2.8 },
]);

// 列表数据
const loading = ref(false);
const productList = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const searchQuery = ref("");

// 搜索表单
const searchForm = reactive({
  status: "",
  keyword: "",
});

// 商品表单数据
const showDrawer = ref(false);
const isEdit = ref(false);
const productFormRef = ref(null);
const productForm = reactive({
  goodsId: null,
  goodsName: "",
  goodsImage: "",
  goodsBrief: "",
  goodsDetail: "",
  originalPrice: 0,
  seckillPrice: 0,
  stock: 0,
  seckillTime: [],
  seckillStatus: 0,
});

// 商品选择输入相关
const productSearchInput = ref("");
const querySearchProduct = (queryString, cb) => {
  const results = allProducts
    .filter(
      (p) => p.name.includes(queryString) || String(p.id).includes(queryString)
    )
    .slice(0, 10)
    .map((p) => ({
      value: `${p.name}（ID:${p.id}）`,
      ...p,
    }));
  cb(results);
};
const handleProductSelect = (item) => {
  productForm.goodsId = item.id;
  productForm.goodsName = item.name;
  productForm.goodsImage = item.image;
  productForm.goodsBrief = item.brief;
  productForm.goodsDetail = item.detail;
  productForm.originalPrice = item.price;
};

// 秒杀状态文本与样式
const seckillStatusText = (status) => {
  switch (status) {
    case 0:
      return "待预热";
    case 1:
      return "预热中";
    case 2:
      return "进行中";
    case 3:
      return "已结束";
    default:
      return "未知";
  }
};
const seckillStatusTagType = (status) => {
  switch (status) {
    case 0:
      return "info";
    case 1:
      return "warning";
    case 2:
      return "success";
    case 3:
      return "danger";
    default:
      return "";
  }
};

// 获取商品列表
const getProductList = () => {
  loading.value = true;
  setTimeout(() => {
    // 假设每个商品有 seckillStatus 字段
    const filtered = allProducts
      .map((p, idx) => ({
        ...p,
        seckillStatus: idx % 4, // 模拟不同状态
        stock: Math.floor(Math.random() * 1000),
        price: p.price,
        image: p.image,
        name: p.name,
        id: p.id,
      }))
      .filter(
        (p) =>
          (!searchForm.status || p.seckillStatus === searchForm.status) &&
          (!searchForm.keyword ||
            p.name.includes(searchForm.keyword) ||
            String(p.id).includes(searchForm.keyword))
      );
    total.value = filtered.length;
    productList.value = filtered.slice(
      (currentPage.value - 1) * pageSize.value,
      (currentPage.value - 1) * pageSize.value + pageSize.value
    );
    loading.value = false;
  }, 500);
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  getProductList();
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  getProductList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getProductList();
};

// 上传成功回调
const handleUploadSuccess = async (options) => {
  try {
    loading.value = true;
    const formData = new FormData();
    formData.append("image", options.file);
    const res = await uploadProductImage(formData);
    if (res.code === 200) {
      productForm.goodsImages = res.data;
      // 直接返回上传结果给组件
      options.onSuccess({
        name: options.file.name,
        url: res.data,
      });
      ElMessage.success("商品图片上传成功");
    } else {
      options.onError(new Error(res.message || "上传失败"));
      ElMessage.error(res.message || "上传失败");
    }
  } catch (error) {
    console.error("上传错误:", error);
    options.onError(error);
    ElMessage.error("上传失败");
  } finally {
    loading.value = false;
  }
};

// 编辑商品
const handleEdit = (row) => {
  isEdit.value = true;
  Object.assign(productForm, row);
  showDrawer.value = true; // 修改这里，从 showAddDialog 改为 showDrawer
};

// 切换商品状态
const handleToggleStatus = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要${row.status === 1 ? "下架" : "上架"}该商品吗？`,
      "提示"
    );
    row.status = row.status === 1 ? 0 : 1;
    ElMessage.success("操作成功");
  } catch (error) {
    console.log("取消操作");
  }
};

// 删除商品
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm("确定要删除该商品吗？", "警告", {
      type: "warning",
    });
    const index = productList.value.findIndex((item) => item.id === row.id);
    if (index !== -1) {
      productList.value.splice(index, 1);
      ElMessage.success("删除成功");
    }
  } catch (error) {
    console.log("取消删除");
  }
};

// 保存商品
const handleSaveProduct = async () => {
  if (!productFormRef.value) return;

  try {
    await productFormRef.value.validate();
    if (isEdit.value) {
      const index = productList.value.findIndex(
        (item) => item.id === productForm.id
      );
      if (index !== -1) {
        productList.value[index] = { ...productForm };
      }
      ElMessage.success("修改成功");
    } else {
      productForm.id = mockProducts.length + 1;
      productForm.status = 1;
      mockProducts.unshift({ ...productForm });
      getProductList();
      ElMessage.success("添加成功");
    }
    showDrawer.value = false; // 修改这里，从 showAddDialog 改为 showDrawer
  } catch (error) {
    console.log("表单验证失败", error);
  }
};

// 新增商品
const handleAdd = () => {
  isEdit.value = false;
  Object.assign(productForm, {
    goodsId: null,
    goodsName: "",
    goodsImage: "",
    goodsBrief: "",
    goodsDetail: "",
    originalPrice: 0,
    seckillPrice: 0,
    stock: 0,
    seckillTime: [],
    seckillStatus: 0,
  });
  productSearchInput.value = "";
  showDrawer.value = true;
};

// 初始化
getProductList();
</script>

<style lang="scss" scoped>
.product-manager {
  padding: 20px;

  .statistics {
    margin-bottom: 20px;

    .el-card {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 20px;
      border-radius: 8px;
      transition: all 0.3s;

      .stat-value {
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 10px;
      }

      .stat-title {
        font-size: 14px;
        color: #666;
        margin-bottom: 5px;
      }

      .stat-trend {
        font-size: 12px;
        &.up {
          color: #67c23a;
        }
        &.down {
          color: #f56c6c;
        }
      }

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      }
    }
  }

  .action-bar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;

    .left {
      display: flex;
      gap: 10px;
    }

    .right {
      display: flex;
      gap: 10px;

      .el-select,
      .el-input {
        min-width: 180px;
      }
    }
  }

  .el-table {
    .el-image {
      width: 60px;
      height: 60px;
      border-radius: 4px;
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .product-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 148px;
    height: 148px;
    display: flex;
    justify-content: center;
    align-items: center;

    &:hover {
      border-color: #409eff;
    }

    .preview-image {
      width: 146px;
      height: 146px;
      object-fit: cover;
    }

    .uploader-icon {
      font-size: 28px;
      color: #8c939d;
    }
  }

  .product-form {
    padding: 20px;
    height: calc(100vh - 120px);
    overflow-y: auto;

    .form-content {
      display: flex;
      gap: 40px;
      margin-bottom: 30px;
      background: #fff;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

      .left-section {
        width: 45%;
      }

      .right-section {
        width: 55%;
      }
    }

    .detail-section {
      background: #fff;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

      .editor-container {
        border: 1px solid #ddd;
        border-radius: 4px;
        width: 100%;

        .toolbar {
          background: #f5f7fa;
          border-bottom: 1px solid #ddd;
        }

        .empty-detail-tip {
          height: 600px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #bbb;
          font-size: 18px;
          background: #fafbfc;
          border-radius: 4px;
        }
      }
    }

    .drawer-footer {
      position: sticky;
      bottom: 0;
      left: 0;
      right: 0;
      padding: 20px;
      background: #fff;
      text-align: right;
      border-top: 1px solid #f0f0f0;
      margin: 0 -20px;

      .el-button {
        margin-left: 8px;
      }
    }
  }

  .category-manager {
    display: flex;
    gap: 20px;

    .category-list {
      flex: 1;
      background: #fff;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

      .el-table {
        .el-table-column {
          text-align: center;
        }
      }
    }

    .category-form {
      flex: 1;
      background: #f9f9f9;
      border-radius: 8px;
      padding: 20px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

      .el-form-item {
        margin-bottom: 15px;
      }
    }
  }

  .category-drawer {
    .el-drawer__body {
      padding: 0 32px 32px 32px;
      background: #f8f9fb;
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
    }
  }

  .category-manager-drawer {
    display: flex;
    flex-direction: row;
    gap: 36px;
    min-height: 400px;

    .category-tree-list {
      flex: 1.1;
      background: #fff;
      border-radius: 10px;
      padding: 24px 12px 12px 12px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
      margin-bottom: 18px;
      min-width: 260px;
      .category-tree {
        min-width: 200px;
      }
    }

    .category-form-upgrade {
      flex: 1.7;
      background: linear-gradient(135deg, #f5f7fa 0%, #e9f0fb 100%);
      border-radius: 10px;
      padding: 36px 28px 24px 28px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);

      .category-input {
        width: 100%;
      }

      .el-form-item {
        margin-bottom: 18px;
      }

      .category-tip {
        margin-top: 24px;
        font-size: 14px;
        color: #999;
        display: flex;
        align-items: center;
        background: #fffbe6;
        border-radius: 4px;
        padding: 10px 16px;
      }
    }
  }
}
</style>
